<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      .wrap {
        width: 800px;
        height: 400px;
        margin: 0 auto;
      }

      table {
        margin: 20px auto;
      }
    </style>
  </head>

  <body>
    <div class="wrap">
      <table cellspacing="20">
        <tr>
          <th><input type="checkbox" value="全选" id="all" /></th>
          <th>产品</th>
          <th>价钱</th>
        </tr>
        <tr>
          <td><input type="checkbox" class="check" /></td>
          <td>iphone</td>
          <td>5000</td>
        </tr>
        <tr>
          <td><input type="checkbox" class="check" /></td>
          <td>iwatch</td>
          <td>2000</td>
        </tr>
        <tr>
          <td><input type="checkbox" class="check" /></td>
          <td>ipad</td>
          <td>3000</td>
        </tr>
      </table>
      <input type="button" class="inverse" value="反选" />
    </div>

    <script>
      //先做全选  获取全选按钮
      var checkAll =  document.getElementById('all');
      // 获取所有要改变的元素
      var checkbox= document.querySelectorAll('.check');
      console.log(checkbox)
      //获取反选按钮
      var inverse = document.querySelector('.inverse');
      checkAll.onclick = function(){
        var stats = checkAll.checked;
       //全选按钮的状态 = 所有元素的状态
        for(var i =0;i<checkbox.length;i++){
          checkbox[i].checked =stats;
        }
      }

      //反选事件
      inverse.onclick = function(){
        for(var i=0;i<checkbox.length;i++){
          checkbox[i].checked =!checkbox[i].checked;
        }
        query()
      }
      //给每个checkbox  循环检测
      for(var i =0;i<checkbox.length;i++){
        checkbox[i].onclick = function(){
          query();
        }
      }

      //检测 要改变的元素状态 是否真正背选中
      function query(){
        //假设已经被全选
        var flag = true;
        //循环 要改变的元素状态 ,遇见没有被选中  改变全选按钮状态
        for(var i=0;i<checkbox.length;i++){
          // if(checkbox[i]==false)
          if(!checkbox[i].checked){
            flag = false;
            break;
          }
        }
        checkAll.checked = flag;
      }
    </script>
  </body>
</html>
